package com.sctvcloud.dongqu.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.FRebellion;
import com.sctvcloud.dongqu.beans.FUsers;
import com.sctvcloud.dongqu.beans.NewsClickCountBean;
import com.sctvcloud.dongqu.beans.NewsIdBean;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.NewsListClickRequestBean;
import com.sctvcloud.dongqu.beans.NewsListClickVo;
import com.sctvcloud.dongqu.beans.SingleResult;
import com.sctvcloud.dongqu.beans.TopicContent;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.http.ParamsEditor;
import com.sctvcloud.dongqu.ui.activities.HudongActivity;
import com.sctvcloud.dongqu.ui.activities.LoginActivity;
import com.sctvcloud.dongqu.ui.activities.MingshengActivity;
import com.sctvcloud.dongqu.ui.activities.MoreServiceActivity;
import com.sctvcloud.dongqu.ui.activities.ShareCommitActivity;
import com.sctvcloud.dongqu.ui.activities.ShareDetailActivity;
import com.sctvcloud.dongqu.ui.adapter.GreatestAdapter;
import com.sctvcloud.dongqu.ui.adapter.MingshengFrgAdapter;
import com.sctvcloud.dongqu.ui.adapter.ShareAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.ShareHolder;
import com.sctvcloud.dongqu.ui.adapter.holder.TopicHolder;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.widget.MyNestedScrollView;
import com.sctvcloud.dongqu.ui.widget.PullToRefreshView;
import com.sctvcloud.dongqu.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.sctvcloud.dongqu.base.BaseActivity.DO_UP_POS;

/**
 * Created by raoweiwei on 2017/8/3.
 * 首页通用的其他列表栏目
 */

public class CommonFuwuFragment extends ColumnBaseFragment implements
        PullToRefreshView.OnHeaderRefreshListener , PullToRefreshView.OnFooterRefreshListener, TopicHolder.OnTopicSelectListener {

    @BindView(R.id.main_pull_refresh_view)
    PullToRefreshView mPullToRefreshView;
    @BindView(R.id.can_content_view1)
    protected RecyclerView mRecyclerView1;
    @BindView(R.id.scroll)
    MyNestedScrollView scroll;


    @BindView(R.id.iv_1)
    protected ImageView iv_1;
    @BindView(R.id.iv_2)
    protected ImageView iv_2;

    private MingshengFrgAdapter mAdapter;
    private boolean mIsLoading = false;
    private List<IListShowData> dataList = new ArrayList<>();

    private List<IListShowData> commonList = new ArrayList<>();
    protected static final int CODE_REQUEST_LOGIN = 303;

    private int mPageNo = 0;
    private int mPageAll = 0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_common_fuwu, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);

        mRecyclerView1.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView1.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView1.addItemDecoration(new RBaseItemDecoration(1));

        iv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MingshengActivity.class);
                intent.putExtra(BaseActivity.EX_TITLE,"志愿服务");
                intent.putExtra(BaseActivity.EX_URL,HomeFragment.getZhiyuna_fuwu());
                startActivity(intent);
            }
        });

        iv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getActivity(), MoreServiceActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString(BaseActivity.EX_URL,HomeFragment.getWangban_life());
                //     bundle.putSerializable(BaseActivity.EX_NEWS_ITEM,govItemBean);
                intent.putExtras(bundle);
                getActivity().startActivity(intent);
            }
        });
        getData();
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

//    @Override
//    public void onResume() {
//        getData();
//        super.onResume();
//    }
//
//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        if(!hidden){
//            getData();
//        }
//        super.onHiddenChanged(hidden);
//    }

    private void getData() {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), HomeFragment.getFuwu(), mPageNo, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }
                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }


                requestNewsClickCount(newsItems, getPageResponse().getData().getTemplate());

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if(mPageNo>0){
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {

            }
        });
    }


    private void initData(List<NewsItem> newsItems, int template) {
        if (mAdapter == null) {
            mAdapter = new MingshengFrgAdapter(getActivity(), null, template).setItemInternalClick(itemClick);
            mRecyclerView1.setAdapter(mAdapter);
        }
        mAdapter.setAct(isAct);

        if (mPageNo == 0) {
            mAdapter.setData(newsItems);
        } else {
            mAdapter.addDatas(newsItems);
        }


    }

    private List<NewsItem> newsItems;

    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(final List<NewsItem> list, final int templete) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (!TextUtils.isEmpty(item.getNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else {
                                        if(item.getNewsType()== Constances.NEWS_TYPE_VIDEO){
                                            item.setViewType(GreatestAdapter.VIEWTYPE_VIDEO);
                                        }
                                        if (!TextUtils.isEmpty(item.getUrlNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    }
                                }
                            }
                        }
                        initData(newsItems, templete);

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onNetFinish();
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mPullToRefreshView.onFooterRefreshComplete();
        mPullToRefreshView.onHeaderRefreshComplete();
        mPullToRefreshView.setEnablePullLoadMoreDataStatus(mPageNo+1 >= mPageAll ? false : true);

    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", tag));
            pairs.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(CommonFuwuFragment.this, "", ((NewsItem) mAdapter.getItem(position)).getNewsTitle(), "", 200, pairs);
            HashMap<String, String> map = new HashMap<>();
            for (Pair<String, String> p : pairs) {
                map.put(p.first, p.second);
            }
            SkipUtil.skipWithNewsItem(getActivity(), (NewsItem) mAdapter.getItem(position), map);
        }
    };








    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPageNo++;
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mPullToRefreshView.onFooterRefreshComplete();
                getData();
            }
        }, 100);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPageNo = 0;
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mPullToRefreshView.onHeaderRefreshComplete();
                getData();

            }
        }, 100);


    }

    @Override
    public void OnTopicSelected(Integer selectInteger, TopicContent tp) {

    }
}
